package com.xmz.cacheaside.thread;

import com.xmz.cacheaside.request.Request;
import com.xmz.cacheaside.request.RequestQueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RequestThreadPool {

    /**
     * 线程池
     */
    private ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public RequestThreadPool() {
        RequestQueue instance = RequestQueue.getInstance();
        for (int i = 0; i < 10; i++) {
            ArrayBlockingQueue<Request> requests = new ArrayBlockingQueue<Request>(100);
            instance.addQueue(requests);
            threadPool.submit(new RequestThread(requests));
        }
    }

    private static class Singleton{
        private static RequestThreadPool requestThreadPool;
        static {
            requestThreadPool=new RequestThreadPool();
        }

        public static RequestThreadPool getRequestThreadPool(){
            return requestThreadPool;
        }
    }

    /**
     * jvm的机制去保证多线程并发安全
     *
     * 内部类的初始化，一定只会发生一次，不管多少个线程并发去初始化
     *
     * @return
     */
    public static RequestThreadPool getInstance() {
        return Singleton.getRequestThreadPool();
    }

    /**
     * 初始化的便捷方法
     */
    public static void init() {
        getInstance();
    }

}
